// index.js
const XLSX = require('../../utils/xlsx.full.min.js')

Page({
  data: {
    numberList: [],
    searchValue: '',
    showList: false,
    filters: []
  },

  // 检查是否为连号
  isConsecutiveNumber(number) {
    for (let i = 0; i < number.length - 2; i++) {
      if (number[i] === number[i + 1] && number[i] === number[i + 2]) {
        return true;
      }
    }
    return false;
  },

  // 检查是否为顺子号
  isSequentialNumber(number) {
    for (let i = 0; i < number.length - 2; i++) {
      const num1 = parseInt(number[i]);
      const num2 = parseInt(number[i + 1]);
      const num3 = parseInt(number[i + 2]);
      
      if ((num1 + 1 === num2 && num2 + 1 === num3) || 
          (num1 - 1 === num2 && num2 - 1 === num3)) {
        return true;
      }
    }
    return false;
  },

  // 检查是否包含4
  containsFour(number) {
    return number.includes('4');
  },

  // 检查是否为爱情号
  isLoveNumber(number) {
    // 检查是否包含520、521
    return number.includes('520') || number.includes('521') || 
           number.includes('1314') || number.includes('7758');
  },

  // 筛选条件变化
  onFilterChange(e) {
    const filters = e.detail.value;
    this.setData({
      filters,
      showList: filters.length > 0 || !!this.data.searchValue
    });

    if (filters.length === 0 && !this.data.searchValue) {
      // 如果没有选中任何筛选条件且没有搜索关键词，清空列表
      this.setData({ numberList: [] });
    } else {
      this.searchNumber(this.data.searchValue);
    }
  },

  // 搜索框输入
  onSearchInput(e) {
    const searchValue = e.detail.value;
    this.setData({ 
      searchValue,
      showList: !!searchValue || this.data.filters.length > 0
    });

    if (!searchValue && this.data.filters.length === 0) {
      // 如果搜索框为空且没有选中任何筛选条件，清空列表
      this.setData({ numberList: [] });
    } else {
      this.searchNumber(searchValue);
    }
  },

  // 高亮显示匹配的数字
  highlightNumber(number, searchValue) {
    let highlightedNumber = number;

    // 高亮搜索关键词
    if (searchValue) {
      const escapedSearchValue = searchValue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const reg = new RegExp(`(${escapedSearchValue})`, 'g');
      highlightedNumber = highlightedNumber.replace(reg, '<span style="color: #ff0000;">$1</span>');
    }

    // 高亮连号
    if (this.data.filters.includes('consecutive')) {
      // 查找连续相同的三个或更多数字
      for (let i = 0; i < number.length - 2; i++) {
        if (number[i] === number[i + 1] && number[i] === number[i + 2]) {
          let j = i + 3;
          while (j < number.length && number[j] === number[i]) {
            j++;
          }
          const consecutiveNumbers = number.substring(i, j);
          highlightedNumber = highlightedNumber.replace(
            consecutiveNumbers,
            `<span style="color: #ff0000;">${consecutiveNumbers}</span>`
          );
          i = j - 1;
        }
      }
    }

    // 高亮顺子号
    if (this.data.filters.includes('sequential')) {
      for (let i = 0; i < number.length - 2; i++) {
        const num1 = parseInt(number[i]);
        const num2 = parseInt(number[i + 1]);
        const num3 = parseInt(number[i + 2]);
        
        if ((num1 + 1 === num2 && num2 + 1 === num3) || 
            (num1 - 1 === num2 && num2 - 1 === num3)) {
          let j = i + 3;
          let isIncreasing = num1 + 1 === num2;
          
          while (j < number.length) {
            const nextNum = parseInt(number[j]);
            if (isIncreasing && parseInt(number[j-1]) + 1 === nextNum) {
              j++;
            } else if (!isIncreasing && parseInt(number[j-1]) - 1 === nextNum) {
              j++;
            } else {
              break;
            }
          }
          
          const sequentialNumbers = number.substring(i, j);
          highlightedNumber = highlightedNumber.replace(
            sequentialNumbers,
            `<span style="color: #ff0000;">${sequentialNumbers}</span>`
          );
          i = j - 1;
        }
      }
    }

    // 高亮爱情号
    if (this.data.filters.includes('love')) {
      const lovePatterns = ['520', '521', '1314', '7758'];
      lovePatterns.forEach(pattern => {
        if (number.includes(pattern)) {
          const reg = new RegExp(pattern, 'g');
          highlightedNumber = highlightedNumber.replace(
            reg,
            `<span style="color: #ff0000;">${pattern}</span>`
          );
        }
      });
    }

    return highlightedNumber;
  },

  // 应用筛选条件
  applyFilters(numbers) {
    const { filters } = this.data;
    return numbers.filter(num => {
      // 如果选择了"不含4"
      if (filters.includes('no4') && this.containsFour(num)) {
        return false;
      }
      
      // 如果选择了"连号"
      if (filters.includes('consecutive') && !this.isConsecutiveNumber(num)) {
        return false;
      }
      
      // 如果选择了"顺子号"
      if (filters.includes('sequential') && !this.isSequentialNumber(num)) {
        return false;
      }

      // 如果选择了"爱情号"
      if (filters.includes('love') && !this.isLoveNumber(num)) {
        return false;
      }
      
      return true;
    });
  },

  // 搜索号码
  searchNumber(searchValue) {
    wx.getStorage({
      key: 'numberList',
      success: (res) => {
        const allNumbers = res.data;
        // 先进行搜索匹配
        let filteredList = allNumbers.filter(num => num.includes(searchValue) || searchValue === '');
        // 再应用筛选条件
        filteredList = this.applyFilters(filteredList);
        
        const highlightedList = filteredList.map(num => ({
          number: num,
          highlightedNumber: this.highlightNumber(num, searchValue)
        }));

        this.setData({ 
          numberList: highlightedList,
          showList: highlightedList.length > 0
        });
        
        console.log('搜索关键词:', searchValue);
        console.log('筛选条件:', this.data.filters);
        console.log('搜索结果:', highlightedList);

        if (highlightedList.length === 0) {
          wx.showModal({
            title: '提示',
            content: '未找到匹配的号码',
            showCancel: false
          });
        }
      },
      fail: () => {
        wx.showModal({
          title: '提示',
          content: '暂无号码数据，请先在我的中导入',
          showCancel: false
        });
      }
    });
  },

  onLoad() {
    this.setData({ 
      numberList: [],
      showList: false,
      filters: []
    });
  }
});
